//
//  LJUserAccount.swift
//  LJWeibo
//
//  Created by Raymond on 15/12/19.
//  Copyright © 2015年 liu. All rights reserved.
//

import UIKit

class LJUserAccount: NSObject, NSCoding {
    
    // 只读属性只要只实现GET方法就行了，而如果只有GET方法可以省略GET
    class var isUserLogin: Bool{
        return LJUserAccount.loadUserAccount() != nil
    }

    var access_token: String?
    
    var uid: String?
    
    var expires_Date: NSDate?
    
    // 这里不能设置为可选类型，否则KVC找不到
    var expires_in: NSTimeInterval = 0{
        didSet{
            expires_Date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    // 用户昵称
    var screen_name: String?
    
    // 用户头像
    var avatar_large: String?
    
    
    init(dict: [String : AnyObject]) {
        super.init()
        
        // KVC 赋值
        setValuesForKeysWithDictionary(dict)
    }
    
    // 没有找到对应的值调用这个方法，避免报错·
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        get{
            return "access_token: \(access_token), uid: \(uid), expires_in: \(expires_in), expires_Date: \(expires_Date)"
        }
    }
    
    // MARK: - 归档和解档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_Date, forKey: "expires_Date")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        
    }
    
    // MARK: - 保存账户信息
    static let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
    
    func saveUserAccount(){
        NSKeyedArchiver.archiveRootObject(self, toFile: LJUserAccount.path)
    }
    
    static var userAccount: LJUserAccount?
    
    func loadUserInfo(finished: (error: NSError?) -> ()){
        LJNetworkTool.shareInstance.loadUserInfo { (result, error) -> () in
            if error != nil && result == nil{
                print("用户数据出错\(error)")
                finished(error: error)
                return
            }
            
            self.screen_name = result!["screen_name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            // 保存
            self.saveUserAccount()
            
            // 更新类属性
            LJUserAccount.userAccount = self
            
            finished(error: nil)
        }
    }
    
    class func loadUserAccount() -> LJUserAccount? {
        // 去内存中查看有没有
        if userAccount == nil{
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? LJUserAccount
        }
        
        if userAccount != nil && userAccount?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
//            print("加载可用数据")
            
            return userAccount
        }
        return nil
    }
}
